﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using SharpDX.RawInput;

namespace Engine
{
    public class KeyboardState
    {
        private static readonly List<Keys> States = new List<Keys>();
        public List<Keys> PressedKeys;

        /// <summary>
        /// Callback функция для обновления состояния.
        /// Должна вызываться во время события: SlimDX.RawInput.Device.KeyboardInput +=  KeyboardState.DeviceOnKeyboardInput;
        /// </summary>
        public static void DeviceOnKeyboardInput(object sender, KeyboardInputEventArgs keyboardInputEventArgs)
        {
            //Console.WriteLine(eventArgs.Key.ToString() + " " + eventArgs.State.ToString());
            switch (keyboardInputEventArgs.State)
            {
                case KeyState.SystemKeyUp:
                case KeyState.KeyUp:
                    while (States.IndexOf(keyboardInputEventArgs.Key) != -1)
                        States.Remove(keyboardInputEventArgs.Key);
                    break;
                case KeyState.SystemKeyDown:
                case KeyState.KeyDown:
                    if (States.IndexOf(keyboardInputEventArgs.Key) == -1)
                        States.Add(keyboardInputEventArgs.Key);
                    break;
                case KeyState.HotKey:
                    throw new NotSupportedException();
                default:
                    throw new NotSupportedException();
            }
        }

        /// <summary>
        /// Опрос одной конкретной клавиши.
        /// </summary>
        /// <param name="key">Клавиша для запроса</param>
        /// <returns>Состояние клавиши (Released | Pressed)</returns>
        public static KeyState GetKeyState(Keys key)
        {
            return States.IndexOf(key) == -1 ? KeyState.KeyUp : KeyState.KeyDown;
        }

        /// <summary>
        /// Копирует текущее состояние клавиш.
        /// </summary>
        /// <returns>Копия текущего состояния клавиатуры.</returns>
        public static KeyboardState GetCurrentState()
        {
            KeyboardState ret = new KeyboardState();
            ret.PressedKeys = new List<Keys>(States);
            return ret;
        }
    }
}